﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Runtime.Serialization;

namespace MesopotamiaLauncher
{
    [RunInstaller(true)]
    public partial class MesopotamiaLauncherInstaller : Installer
    {
        internal const string ConfigFile = "Mes.config";

        /// <summary>
        /// files used in screen saver
        /// </summary>
        private readonly string[] _screenSaverFiles = new[]
                                                          {
                                                              "Meso.scr",
                                                              MesopotamiaLauncherInstaller.ConfigFile
                                                          };

        public MesopotamiaLauncherInstaller()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Remove the screen saver from the windows folder
        /// </summary>
        private void RemoveScreenSaver()
        {
            try
            {
                foreach (string file in _screenSaverFiles)
                {
                    string removeFile = Environment.GetEnvironmentVariable("SystemRoot") + @"\System32\" + file;
                    // remove file
                    if (System.IO.File.Exists(removeFile))
                    {
                        System.IO.File.Delete(removeFile);
                    }
                    else
                    {
                        MiniLogger.LogDebug("Unable to remove file " + removeFile);
                    }
                }
            }
            catch (Exception ex)
            {
                MiniLogger.LogDebug("Error removing file" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// Copy the screen saver files into the windows folder
        /// </summary>
        private void CopyScreenSaver()
        {
            try
            {
                foreach (string file in _screenSaverFiles)
                {
                    string sourceFile = (Context.Parameters["targetdir"] + file).Replace("scr", "exe");
                    string destinationFile = Environment.GetEnvironmentVariable("SystemRoot") + @"\System32\" + file;

                    // copy file
                    if (System.IO.File.Exists(sourceFile))
                    {
                        System.IO.File.Copy(sourceFile, destinationFile);
                    }
                    else
                    {
                        MiniLogger.LogDebug("Unable to copy file " + sourceFile + ":" + destinationFile);
                    }
                }
            }
            catch (Exception ex)
            {
                MiniLogger.LogDebug("Exception copying files "+ ex.Message);
                throw;
            }

        }

        /// <summary>
        /// Uninstall the app, remove the screen saver files
        /// </summary>
        /// <param name="savedState"></param>
        protected override void OnAfterUninstall(IDictionary savedState)
        {

            base.OnAfterUninstall(savedState);

            // remove screen saver
            RemoveScreenSaver();
        }

        /// <summary>
        /// on after install, remove old files, save install path, copy new files
        /// </summary>
        /// <param name="savedState"></param>
        protected override void OnAfterInstall(IDictionary savedState)
        {
            base.OnAfterInstall(savedState);

            // remove screen saver
            RemoveScreenSaver();

            // update the config with the new install path
            UpdateConfigInstallPath();

            // copy screen saver
            CopyScreenSaver();
        }

        /// <summary>
        /// Update the config folder to the install path
        /// </summary>
        private void UpdateConfigInstallPath()
        {
            string configFilePath = Context.Parameters["targetdir"] + @"\" + MesopotamiaLauncherInstaller.ConfigFile;
            var mesFiles = new MesoptamiaFiles
                               {
                                   MesopotamiaExecutable = "PW.exe",
                                   MesopotamiaPath = Context.Parameters["targetdir"]
                               };

            // update the config file
            try
            {
                using (System.IO.Stream sw = new System.IO.FileStream(configFilePath, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                {
                    var dataContractSerializer = new DataContractSerializer(mesFiles.GetType());
                    dataContractSerializer.WriteObject(sw, mesFiles);
                }
            }
            catch (Exception ex)
            {
                MiniLogger.LogDebug("Error Serializing data "+ ex.Message);
                throw;
            }
        }
    }
}


